package com.sxfq.loansupermarket.backsystem.modular.basicData.controller;

import com.sxfq.loansupermarket.backsystem.common.annotion.log.BussinessLog;
import com.sxfq.loansupermarket.backsystem.common.constant.Dict;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.ConstantFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.node.ZTreeNode;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.MediumMapper;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Medium;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.LogObjectHolder;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.basicData.dao.MediumDao;
import com.sxfq.loansupermarket.backsystem.modular.basicData.service.IMediumService;
import com.sxfq.loansupermarket.backsystem.modular.system.warpper.MediumWarpper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 媒介控制器
 *
 * @author fengshuonan
 * @Date 2017年2月17日20:27:22
 */
@Controller
@RequestMapping("/medium")
public class MediumController extends BaseController {

    private String PREFIX = "/basicData/medium/";

    @Resource
    MediumDao mediumDao;

    @Resource
    MediumMapper mediumMapper;

    @Resource
    IMediumService mediumService;

    /**
     * 跳转到媒介管理首页
     */
    @RequestMapping("")
    public String index() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "medium.html";
    }

    /**
     * 跳转到添加媒介
     */
    @RequestMapping("/medium_add")
    public String mediumAdd() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "medium_add.html";
    }

    /**
     * 跳转到修改媒介
     */
    @RequestMapping("/medium_update/{mediumId}")
    public String mediumUpdate(@PathVariable Integer mediumId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        Medium medium = mediumMapper.selectById(mediumId);
        model.addAttribute(medium);
        model.addAttribute("mName", ConstantFactory.me().getMediumName(medium.getPid()));
        LogObjectHolder.me().set(medium);
        return PREFIX + "medium_edit.html";
    }

    /**
     * 获取媒介的tree列表
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> tree() {
        List<ZTreeNode> tree = this.mediumDao.tree();
        tree.add(ZTreeNode.createParent());
        return tree;
    }

    /**
     * 新增媒介
     */
    @BussinessLog(value = "添加媒介", key = "mediumName", dict = Dict.MediumDict)
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Medium medium) {
        if (ToolUtil.isOneEmpty(medium, medium.getMediumname())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        //完善pids,根据pid拿到pid的pids
        mediumSetPids(medium);
        return this.mediumMapper.insert(medium);
    }

    /**
     * 获取所有媒介列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        List<Map<String, Object>> list = this.mediumDao.list(condition);
        return super.warpObject(new MediumWarpper(list));
    }

    /**
     * 媒介详情
     */
    @RequestMapping(value = "/detail/{mediumId}")
    @ResponseBody
    public Object detail(@PathVariable("mediumId") Integer mediumId) {
        return mediumMapper.selectById(mediumId);
    }

    /**
     * 修改媒介
     */
    @BussinessLog(value = "修改媒介", key = "simplename", dict = Dict.MediumDict)
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Medium medium) {
        if (ToolUtil.isEmpty(medium) || medium.getId() == null) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        mediumSetPids(medium);
        mediumMapper.updateById(medium);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除媒介
     */
    @BussinessLog(value = "删除媒介", key = "mediumId", dict = Dict.DeleteDict)
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer mediumId) {

        //缓存被删除的媒介名称
        LogObjectHolder.me().set(ConstantFactory.me().getMediumName(mediumId));

        mediumService.deleteMedium(mediumId);

        return SUCCESS_TIP;
    }

    private void mediumSetPids(Medium medium) {
        if (ToolUtil.isEmpty(medium.getPid()) || "0".equals(medium.getPid()+"")) {
            medium.setPid(0);
            medium.setPids("[0],");
        } else {
            int pid = medium.getPid();
            Medium temp = mediumMapper.selectById(pid);
            String pids = temp.getPids();
            medium.setPid(pid);
            medium.setPids(pids + "[" + pid + "],");
        }
    }

    @RequestMapping(value = "/getMedium", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String, Object>> getMedium() {
        List<Map<String, Object>> mediumList = mediumService.getMedium();
        return mediumList;
    }

    @RequestMapping(value = "/getThrMedium", method = RequestMethod.POST)
    @ResponseBody
    public List<Medium> getThrMedium() {
        List<Medium> mediumList = mediumService.getThrMedium();
        return mediumList;
    }
}
